<template>
  <div class="message-list">
    <div class="header">
      <h2>消息列表</h2>
    </div>
    <div class="conversation-list">
      <div v-for="conv in conversations" 
           :key="conv.partner_id" 
           class="conversation-item" 
           @click="openChat(conv)"
           :class="{ 'has-unread': conv.unread_count > 0 }">
        <!-- 头像区域 -->
        <div class="avatar" :style="{ backgroundColor: getRandomColor(conv.partner_id) }">
          <span class="avatar-text">{{ conv.partner_name?.[0] || 'U' }}</span>
        </div>

        <!-- 消息内容 -->
        <div class="content">
          <div class="header-info">
            <span class="partner-name">{{ conv.partner_name }}</span>
            <span class="last-time">{{ formatTime(conv.last_time) }}</span>
          </div>
          <div class="message-preview">{{ conv.last_message }}</div>
        </div>

        <!-- 未读消息数量 -->
        <div v-if="conv.unread_count > 0" class="unread-badge">
          {{ conv.unread_count }}
        </div>
      </div>
    </div>

    <!-- 空状态：暂无消息 -->
    <div v-if="conversations.length === 0" class="empty-state">
      <i class="el-icon-chat-dot-square"></i>
      <p>暂无消息</p >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineExpose } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'

const router = useRouter()
const conversations = ref([])

// 获取会话列表
const fetchConversations = async () => {
  try {
    console.log('正在获取消息列表...')
    const userId = localStorage.getItem('userId')
    const response = await axios.get('/chat/messages/conversations', {
      params: { user_id: userId }
    })

    console.log('获取消息列表响应:', response)
    if (response.data.status === 200) {
      conversations.value = response.data.data
      console.log('更新会话列表成功，数量:', conversations.value.length)
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
  }
}

// 格式化时间
const formatTime = (time) => {
  const now = dayjs()
  const messageTime = dayjs(time)

  if (now.diff(messageTime, 'day') === 0) {
    return messageTime.format('HH:mm')
  } else if (now.diff(messageTime, 'day') === 1) {
    return '昨天'
  } else if (now.diff(messageTime, 'year') === 0) {
    return messageTime.format('MM-DD')
  }
  return messageTime.format('YYYY-MM-DD')
}

// 生成随机颜色
const getRandomColor = (id) => {
  const colors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C',
    '#909399', '#9B59B6', '#2ECC71', '#3498DB'
  ]
  return colors[id % colors.length]
}

// 打开聊天窗口
const openChat = (conversation) => {
  // 检查当前是否在用户中心页面
  const isInUserCenter = window.location.pathname.includes('/user');
  
  router.push({
    name: 'chat',
    query: { 
      partner_id: conversation.partner_id, 
      partner_name: conversation.partner_name,
      from_user_center: isInUserCenter ? '1' : '0',
      active_tab: isInUserCenter ? 'messages' : ''
    }
  })
}

onMounted(() => {
  fetchConversations()
})

// 将方法暴露给父组件
defineExpose({
  fetchConversations
})
</script>

<style scoped>
.message-list {
  height: 100vh;
  background-color: #f7f9fb;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0;
  font-size: 22px;
  color: #333;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.conversation-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.has-unread {
  background-color: #e6f7ff;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  transition: transform 0.3s ease;
}

.conversation-item:hover .avatar {
  transform: scale(1.1);
}

.avatar-text {
  color: white;
  font-size: 24px;
  font-weight: 500;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
 /* align-items: flex-start; /* 左对齐 */
}

.header-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.partner-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.last-time {
  font-size: 13px;
  color: #999;
}

.message-preview {
  color: #606266;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left; /* 左对齐 */
}

.unread-badge {
  background-color: #f56c6c;
  color: white;
  border-radius: 12px;
  min-width: 22px;
  height: 22px;
  padding: 0 8px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 15px;
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}
</style>